<template>
  <div class="appointment-customers-container">
    <!-- 顶部导航标签 -->
    <div class="top-tabs">
      <div
        class="tab-item active"
        @click="switchTab('appointment')"
      >
        预约上门
      </div>
      <div
        class="tab-item"
        @click="switchTab('realtime')"
      >
        实时展示
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <div class="left-section">
        <el-select v-model="searchType" placeholder="按编号" style="width: 100px; margin-right: 8px;">
          <el-option label="按编号" value="number" />
          <el-option label="按姓名" value="name" />
          <el-option label="按电话" value="phone" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="请搜索客户"
          :prefix-icon="Search"
          clearable
          style="width: 200px; margin-right: 8px;"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
      </div>

      <div class="right-section">
        <el-dropdown>
          <el-button size="small">
            常用筛选
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="showCommonFilter">常用筛选</el-dropdown-item>
              <el-dropdown-item @click="showAdvancedFilter">高级筛选</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
        @sort-change="handleSortChange"
      >
        <el-table-column type="index" label="序号" width="80" />

        <el-table-column prop="customerName" label="客户姓名" min-width="150">
          <template #default="{ row }">
            <div class="customer-name-cell">
              <span class="name-text">{{ row.customerName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="phoneNumber" label="手机号码" width="140">
          <template #default="{ row }">
            <span>{{ row.phoneNumber }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="customerType" label="客户类型" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="getCustomerTypeTag(row.customerType).type">
              {{ row.customerType }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="arrivedAtStore" label="是否到店" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="row.arrivedAtStore ? 'success' : 'danger'">
              {{ row.arrivedAtStore ? '已到店' : '暂未到店' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="appointmentTime" label="预约时间" width="160">
          <template #default="{ row }">
            <span>{{ row.appointmentTime }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="arrivalTime" label="到店时间" width="160">
          <template #default="{ row }">
            <span>{{ row.arrivalTime || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="firstVisit" label="首次到店" width="100">
          <template #default="{ row }">
            <span>{{ row.firstVisit ? '是' : '否' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="lastOperation" label="上次操作" width="120">
          <template #default="{ row }">
            <span>{{ row.lastOperation || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="text" size="small" @click="handleConfirmArrival(row)">
                确认到店
              </el-button>
              <span class="divider">|</span>
              <el-button type="text" size="small" @click="handleReschedule(row)">
                改约
              </el-button>
              <span class="divider">|</span>
              <el-button type="text" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <div class="pagination-left">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handleCurrentChange"
          />
        </div>

        <div class="pagination-center">
          <span>到第</span>
          <el-input
            v-model="jumpPage"
            size="small"
            style="width: 60px; margin: 0 8px;"
            @keyup.enter="handleJumpPage"
          />
          <span>页</span>
          <el-button size="small" @click="handleJumpPage">确定</el-button>
        </div>

        <div class="pagination-right">
          <span>共{{ total }}条</span>
          <el-select v-model="pageSize" size="small" style="width: 80px; margin-left: 8px;" @change="handleSizeChange">
            <el-option label="10条/页" :value="10" />
            <el-option label="20条/页" :value="20" />
            <el-option label="50条/页" :value="50" />
            <el-option label="100条/页" :value="100" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 确认到店对话框 -->
    <el-dialog v-model="confirmArrivalVisible" title="确认到店" width="400px">
      <el-form :model="arrivalForm" label-width="100px">
        <el-form-item label="客户姓名">
          <span>{{ currentCustomer?.customerName }}</span>
        </el-form-item>
        <el-form-item label="预约时间">
          <span>{{ currentCustomer?.appointmentTime }}</span>
        </el-form-item>
        <el-form-item label="到店时间" required>
          <el-date-picker
            v-model="arrivalForm.arrivalTime"
            type="datetime"
            placeholder="选择到店时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="arrivalForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="confirmArrivalVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmArrival">确定</el-button>
      </template>
    </el-dialog>

    <!-- 改约对话框 -->
    <el-dialog v-model="rescheduleVisible" title="改约" width="400px">
      <el-form :model="rescheduleForm" label-width="100px">
        <el-form-item label="客户姓名">
          <span>{{ currentCustomer?.customerName }}</span>
        </el-form-item>
        <el-form-item label="原预约时间">
          <span>{{ currentCustomer?.appointmentTime }}</span>
        </el-form-item>
        <el-form-item label="新预约时间" required>
          <el-date-picker
            v-model="rescheduleForm.newAppointmentTime"
            type="datetime"
            placeholder="选择新的预约时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="改约原因">
          <el-input
            v-model="rescheduleForm.reason"
            type="textarea"
            placeholder="请输入改约原因"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rescheduleVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReschedule">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ArrowDown } from '@element-plus/icons-vue'

// 响应式数据
const tableRef = ref()
const searchType = ref('number')
const searchKeyword = ref('')
const activeTab = ref('appointment')
const jumpPage = ref(1)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(9425)

// 对话框状态
const confirmArrivalVisible = ref(false)
const rescheduleVisible = ref(false)
const currentCustomer = ref<any>(null)

// 表单数据
const arrivalForm = ref({
  arrivalTime: null,
  remark: ''
})

const rescheduleForm = ref({
  newAppointmentTime: null,
  reason: ''
})

// 表格数据
const tableData = ref<any[]>([])

// 模拟数据
const mockData = [
  {
    id: 1,
    customerName: '张跃(237772)',
    phoneNumber: '182****9800',
    customerType: '潜在客户',
    arrivedAtStore: false,
    appointmentTime: '2024-04-30 上午',
    arrivalTime: '',
    firstVisit: true,
    lastOperation: ''
  },
  {
    id: 2,
    customerName: '孙兵(263159)',
    phoneNumber: '173****0294',
    customerType: '意向客户',
    arrivedAtStore: false,
    appointmentTime: '2024-06-18 上午',
    arrivalTime: '',
    firstVisit: false,
    lastOperation: '202'
  },
  {
    id: 3,
    customerName: '杜女士(304759)',
    phoneNumber: '158****2153',
    customerType: '需求客户',
    arrivedAtStore: false,
    appointmentTime: '2024-08-15 上午',
    arrivalTime: '',
    firstVisit: true,
    lastOperation: ''
  },
  {
    id: 4,
    customerName: '李军久(181057)',
    phoneNumber: '139****5415',
    customerType: '潜在客户',
    arrivedAtStore: false,
    appointmentTime: '2024-09-27 下午',
    arrivalTime: '',
    firstVisit: true,
    lastOperation: ''
  },
  {
    id: 5,
    customerName: '王先生(123456)',
    phoneNumber: '138****5678',
    customerType: '意向客户',
    arrivedAtStore: false,
    appointmentTime: '2024-10-15 上午',
    arrivalTime: '',
    firstVisit: false,
    lastOperation: ''
  }
]

// 获取客户类型标签样式
const getCustomerTypeTag = (type: string) => {
  switch (type) {
    case '潜在客户':
      return { type: 'success', text: type }
    case '意向客户':
      return { type: 'warning', text: type }
    case '需求客户':
      return { type: 'success', text: type }
    default:
      return { type: 'info', text: type }
  }
}

// 获取表格数据
const fetchData = () => {
  // 模拟分页数据
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  tableData.value = mockData.slice(start, end)
}

// 切换标签
const switchTab = (tab: string) => {
  activeTab.value = tab
  if (tab === 'realtime') {
    ElMessage.info('实时展示功能待实现')
  }
  currentPage.value = 1
  fetchData()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 显示常用筛选
const showCommonFilter = () => {
  ElMessage.info('常用筛选功能待实现')
}

// 显示高级筛选
const showAdvancedFilter = () => {
  ElMessage.info('高级筛选功能待实现')
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  jumpPage.value = page
  fetchData()
}

// 跳转页面
const handleJumpPage = () => {
  const page = parseInt(jumpPage.value.toString())
  if (page >= 1 && page <= Math.ceil(total.value / pageSize.value)) {
    currentPage.value = page
    fetchData()
  } else {
    ElMessage.warning('请输入有效的页码')
  }
}

// 排序处理
const handleSortChange = ({ prop, order }: any) => {
  console.log('排序:', prop, order)
  // 这里可以实现排序逻辑
}

// 确认到店
const handleConfirmArrival = (row: any) => {
  currentCustomer.value = row
  arrivalForm.value = {
    arrivalTime: new Date(),
    remark: ''
  }
  confirmArrivalVisible.value = true
}

const confirmArrival = () => {
  if (!arrivalForm.value.arrivalTime) {
    ElMessage.warning('请选择到店时间')
    return
  }

  // 更新客户状态
  const customer = tableData.value.find(item => item.id === currentCustomer.value.id)
  if (customer) {
    customer.arrivedAtStore = true
    customer.arrivalTime = arrivalForm.value.arrivalTime.toLocaleString()
  }

  ElMessage.success('确认到店成功')
  confirmArrivalVisible.value = false
}

// 改约
const handleReschedule = (row: any) => {
  currentCustomer.value = row
  rescheduleForm.value = {
    newAppointmentTime: null,
    reason: ''
  }
  rescheduleVisible.value = true
}

const confirmReschedule = () => {
  if (!rescheduleForm.value.newAppointmentTime) {
    ElMessage.warning('请选择新的预约时间')
    return
  }

  // 更新预约时间
  const customer = tableData.value.find(item => item.id === currentCustomer.value.id)
  if (customer) {
    const timeStr = rescheduleForm.value.newAppointmentTime.toLocaleString()
    customer.appointmentTime = timeStr
  }

  ElMessage.success('改约成功')
  rescheduleVisible.value = false
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这个预约记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      total.value--
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.appointment-customers-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;

  // 顶部标签
  .top-tabs {
    display: flex;
    background: white;
    border-radius: 8px 8px 0 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 0;

    .tab-item {
      padding: 12px 24px;
      cursor: pointer;
      font-size: 14px;
      color: #606266;
      border-bottom: 2px solid transparent;
      transition: all 0.3s ease;

      &:hover {
        color: #409eff;
        background-color: #f0f9ff;
      }

      &.active {
        color: #409eff;
        border-bottom-color: #409eff;
        background-color: #f0f9ff;
        font-weight: 500;
      }
    }
  }

  // 搜索和筛选区域
  .search-filter-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 16px 20px;
    border-bottom: 1px solid #e6e6e6;

    .left-section {
      display: flex;
      align-items: center;
    }

    .right-section {
      display: flex;
      align-items: center;
    }
  }

  // 表格容器
  .table-container {
    background: white;
    border-radius: 0 0 8px 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .customer-name-cell {
      .name-text {
        font-weight: 500;
        color: #303133;
      }
    }

    .action-buttons {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-button {
        padding: 0;
        color: #409eff;
        font-size: 12px;

        &:hover {
          color: #66b1ff;
        }
      }

      .divider {
        color: #dcdfe6;
        font-size: 12px;
      }
    }

    .pagination-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-top: 1px solid #e6e6e6;
      background-color: #fafafa;

      .pagination-left {
        flex: 1;
      }

      .pagination-center {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: #606266;

        .el-input {
          .el-input__inner {
            text-align: center;
          }
        }
      }

      .pagination-right {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        color: #606266;
        flex: 1;
        justify-content: flex-end;
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .appointment-customers-container {
    .search-filter-section {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;

      .left-section,
      .right-section {
        justify-content: center;
      }
    }

    .table-container {
      .pagination-container {
        flex-direction: column;
        gap: 12px;

        .pagination-left,
        .pagination-center,
        .pagination-right {
          justify-content: center;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .appointment-customers-container {
    padding: 12px;

    .top-tabs {
      .tab-item {
        padding: 12px 16px;
        font-size: 13px;
      }
    }

    .search-filter-section {
      padding: 12px;

      .left-section,
      .right-section {
        flex-wrap: wrap;
        gap: 8px;
      }
    }

    .table-container {
      .pagination-container {
        padding: 12px;

        .pagination-center {
          flex-wrap: wrap;
          gap: 4px;
        }
      }
    }
  }
}
</style>
